/*

Frequency of use: 1 2 3 4 [5] HIGH

Short:
    Observer is used to watch events on another object.  Here, the Writer class 
keeps an eye on the MessageBoard class, and writes the message each time 
MessageBoard::post() is called.

Long:
    The observer pattern (a subset of the asynchronous publish/subscribe 
pattern) is a software design pattern in which an object, called the subject, 
maintains a list of its dependents, called observers, and notifies them 
automatically of any state changes, usually by calling one of their methods. It 
is mainly used to implement distributed event handling systems.

Information sources:
 - http://calumgrant.net/patterns/index.html
 - http://en.wikipedia.org/wiki/Observer_pattern
 - http://www.dofactory.com/Patterns/Patterns.aspx
*/

#include <iostream>
#include <string>

class Observer
{
public:
	virtual ~Observer() { }
	virtual void on_message(const std::string &)=0;
};

class MessageBoard
{
	Observer & observer;
public:
	MessageBoard(Observer & obs) : observer(obs) { }

	void post(const std::string & str)
	{
		observer.on_message(str);
	};
};

class Writer : public Observer
{
public:
	void on_message(const std::string & str)
	{
		std::cout << str << std::endl;
	}
};

void hello_world(MessageBoard & message_board)
{
	message_board.post("Hello world!");
}

int main()
{
	Writer writer;
	MessageBoard message_board(writer);
	hello_world(message_board);
	return 0;
}

